package com.itic.mall.system.project.livingRate.service;

import com.itic.appbase.applications.sys.syssetting.service.SysSettingService;
import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.common.service.CrudService;
import com.itic.appbase.framework.type.LivingRateType;
import com.itic.appbase.framework.type.SysSettingType;
import com.itic.appbase.framework.utils.DateHelper;
import com.itic.appbase.framework.utils.NumberStringHelper;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.mall.mobile.users.livingRate.entity.LivingRateResultVo;
import com.itic.mall.mobile.users.livingRate.entity.LivingRateVo;
import com.itic.mall.system.inter.finance.makeMoney.persistence.model.FinanceUserMakeMoney;
import com.itic.mall.system.inter.finance.makeMoney.service.FinanceUserMakeMoneyService;
import com.itic.mall.system.inter.project.livingRate.persistence.dao.LivingRateDao;
import com.itic.mall.system.inter.project.livingRate.persistence.model.LivingRate;
import com.itic.mall.system.inter.project.livingRate.persistence.model.LivingRateExample;
import com.itic.mall.system.inter.project.livingRate.persistence.model.LivingRateExample.Criteria;
import com.itic.mall.system.inter.project.livingRateCondition.persistence.model.LivingRateCondition;
import com.itic.mall.system.inter.users.usersmall.persistence.model.UsersMall;
import com.itic.mall.system.orders.item.service.OrdersItemService;
import com.itic.mall.system.project.livingRateCondition.service.LivingRateConditionService;
import com.itic.mall.system.users.shareLog.service.UsersShareLogService;
import com.itic.mall.system.users.useLog.service.UseLogService;
import com.itic.mall.system.users.userHelp.service.UsersHelpService;
import com.itic.mall.system.users.usersmall.service.UsersMallService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;


@Service
@Transactional
public class LivingRateService
     extends CrudService<LivingRateDao,LivingRate,LivingRateExample> {
    @Autowired
    private LivingRateDao livingRateDao;
    @Autowired
    private UsersMallService usersMallService;
    @Autowired
    private LivingRateConditionService livingRateConditionService;
    
    @Autowired
    private UsersShareLogService usersShareLogService;
    @Autowired
    private OrdersItemService ordersItemService;
    @Autowired
    private SysSettingService sysSettingService;
    @Autowired
    private FinanceUserMakeMoneyService financeUserMakeMoneyService;
    @Autowired
    private UseLogService useLogService;
    @Autowired
    private UsersHelpService usersHelpService;
    private static final int RateDays = 7;
    
    /***
     * 计算用户的年利率
     * @param usersMall
     */
    public LivingRateResultVo calUserLivingRate(UsersMall usersMall) {
    	String minPercent = this.sysSettingService.getByKey(SysSettingType.LIVING_RATE_MIN_PERCENT.toString());
    	String maxPercent = this.sysSettingService.getByKey(SysSettingType.LIVING_RATE_MAX_PERCENT.toString());
    	String differPercent = NumberStringHelper.subtractString(maxPercent, minPercent);
    	double typePercent = 0;
    	LivingRateResultVo resultVo = new LivingRateResultVo();
    	LivingRateVo inviteRateVo = this.calUserConditionRate(LivingRateType.Invite, usersMall,differPercent);
    	resultVo.setInviteMarks(inviteRateVo.getMarks());
    	resultVo.setInviteRate(inviteRateVo.getRate());
    	resultVo.setInviteState(inviteRateVo.getState());
    	typePercent+=inviteRateVo.getRate();
    	LivingRateVo consumeRateVo = this.calUserConditionRate(LivingRateType.Cousume, usersMall,differPercent);
    	resultVo.setConsumeMarks(consumeRateVo.getMarks());
    	resultVo.setConsumeRate(consumeRateVo.getRate());
    	resultVo.setConsumeState(consumeRateVo.getState());
    	//typePercent+=consumeRateVo.getRate();
    	LivingRateVo shareRateVo = this.calUserConditionRate(LivingRateType.Share, usersMall,differPercent);
    	resultVo.setShareMarks(shareRateVo.getMarks());
    	resultVo.setShareRate(shareRateVo.getRate());
    	resultVo.setShareState(shareRateVo.getState());
    	typePercent+=shareRateVo.getRate();
    	LivingRateVo shoppingRateVo = this.calUserConditionRate(LivingRateType.Shopping, usersMall,differPercent);
    	resultVo.setShoppingMarks(shoppingRateVo.getMarks());
    	resultVo.setShoppingRate(shoppingRateVo.getRate());
    	resultVo.setShoppingState(shoppingRateVo.getState());
    	typePercent+=shoppingRateVo.getRate();
    	LivingRateVo useRateVo = this.calUserConditionRate(LivingRateType.Use, usersMall,differPercent);
    	resultVo.setUseMarks(useRateVo.getMarks());
    	resultVo.setUseRate(useRateVo.getRate());
    	resultVo.setUseState(useRateVo.getState());
    	typePercent+=useRateVo.getRate();
    	LivingRateVo commissionRateVo = this.calUserConditionRate(LivingRateType.CommissionRate, usersMall,differPercent);
    	resultVo.setCommissionMarks(commissionRateVo.getMarks());
    	resultVo.setCommissionRate(commissionRateVo.getRate());
    	resultVo.setCommissionState(commissionRateVo.getState());
    	typePercent+=commissionRateVo.getRate();
    	String yearPercent = NumberStringHelper.addString(minPercent, Double.toString(typePercent));
    	double totalHelpRate = this.usersHelpService.getUsersHelpTotalRate(usersMall.getId());
    	yearPercent = NumberStringHelper.addString(yearPercent, Double.toString(totalHelpRate));
    	yearPercent = NumberStringHelper.round(yearPercent, 2);
    	resultVo.setYearRate(Double.parseDouble(yearPercent));
    	boolean flag = this.compareYearRateWithToday(yearPercent, usersMall.getId());
        if(flag)
        	resultVo.setYeatRateState("up");
        else
        	resultVo.setYeatRateState("down");
        return resultVo;
    }
    
    /**
     * 计算用户的条件类型的利率
     * @param usersMall
     */
    public LivingRateVo calUserConditionRate(LivingRateType type,UsersMall usersMall,String differPercent) {
    	LivingRate livingRate = this.getLivingRateByType(type);
    	int days = livingRate.getDays()==null?RateDays:livingRate.getDays();
    	Date date = DateHelper.addDays(DateHelper.parseDate(DateHelper.getDate()), 0-days);
    	Double count = null;
    	switch (type) {
			case Invite:
				int inviteCount = this.usersMallService.getUserInviteCountLatelyDays(usersMall.getId(),date);
				count = Double.valueOf(inviteCount);
				break;
			case Cousume:
				count = this.ordersItemService.getUserConsumeByDays(usersMall.getId(), date);
				break;
			case Share:
				int shareCount = this.usersShareLogService.getUserShareCount(usersMall.getId(), date);
				count = Double.valueOf(shareCount);
				break;
			case Use:
				int useCount=this.useLogService.getUserLateUseCount(usersMall.getId(), date);
				count = Double.valueOf(useCount);
				break;
			case Shopping:
				int shoppingCount = this.ordersItemService.getUserShoppingCountByDays(usersMall.getId(), date);
				//int shoppingCount = this.ordersItemService.getUserShoppingCountByDays(usersMall.getId(), date);
				count = Double.valueOf(shoppingCount);
				break;
			case CommissionRate:
				count = this.ordersItemService.getUserCommissionRateCountByDays(usersMall.getId(), date);
				break;
    	}
    	LivingRateCondition livingRateCondition = this.livingRateConditionService.getFullLivingRate(type,count);
    	LivingRateVo livingRateVo = this.calLivingRatePerType(usersMall.getId(),livingRateCondition, livingRate,differPercent);
    	return livingRateVo;
    }
    /**
     * 计算每个类型的百分比和分数
     * @param livingRateCondition
     * @param livingRate
     * @return LivingRateVo rate 百分比  marks 分数比例 
     */
    public LivingRateVo calLivingRatePerType(String userId,LivingRateCondition livingRateCondition,LivingRate livingRate,String differPercent) {
    	if(livingRateCondition == null)
    		return new LivingRateVo(0, 0);
    	double minPercent = livingRate.getMinPercent();
    	double maxPercent = livingRate.getMaxPercent();
    	double fullMarks = livingRate.getFullMarks();
    	double marks = livingRateCondition.getMarks();
    	String calmarks = NumberStringHelper.divString(Double.toString(marks), Double.toString(fullMarks), 2);
    	String calPercent = NumberStringHelper.mulString(Double.toString(maxPercent),calmarks);
    	if(Double.parseDouble(calPercent)<=minPercent)
    		calPercent = Double.toString(minPercent);
    	calPercent = NumberStringHelper.divString(calPercent, "100", 2);
    	calPercent =  NumberStringHelper.mulString(calPercent,differPercent);
    	LivingRateVo vo = new LivingRateVo(Double.parseDouble(calPercent),Double.parseDouble(calmarks));
    	boolean flag = this.compareLivingRateWithToday(calmarks, userId, livingRate);
    	if(flag)
    		vo.setState("up");
    	else
    		vo.setState("down");
    	return vo;
    }
    /**
     * 当前分数与前一天的分数进行比较
     * @param marks
     * @param userId
     * @param livingRate
     * @return
     */
    public boolean compareLivingRateWithToday(String marks,String userId,LivingRate livingRate) {
    	boolean flag = true;
    	FinanceUserMakeMoney todayMakeMoney = this.financeUserMakeMoneyService.getUserTodayFinanceUserMakeMoney(userId);
    	if(todayMakeMoney ==null)
    		return flag;
    	String todayMoney ="0";
    	LivingRateType livingRateType = LivingRateType.getLivingRateType(livingRate.getType());
    	switch (livingRateType) {
			case Invite:
				todayMoney = Double.toString(todayMakeMoney.getInviteMarks());
				break;
			case Cousume:
				todayMoney = Double.toString(todayMakeMoney.getConsumeMarks());
				break;
			case Share:
				todayMoney = Double.toString(todayMakeMoney.getShareMakrs());
				break;
			case Use:
				todayMoney = Double.toString(todayMakeMoney.getUseMarks());
				break;
			case Shopping:
				todayMoney = Double.toString(todayMakeMoney.getShoppingMarks());
				break;
			case CommissionRate:
				todayMoney = Double.toString(todayMakeMoney.getCommissionMarks());
				break;
		}
    	
    	flag = NumberStringHelper.isGreater(marks, todayMoney);
    	return flag;
    }
    /**
     * 今天的年利率与前一天的进行比较
     * @param yearRate
     * @param userId
     * @return
     */
    public boolean compareYearRateWithToday(String yearRate,String userId) {
    	boolean flag = true;
    	FinanceUserMakeMoney todayMakeMoney = this.financeUserMakeMoneyService.getUserTodayFinanceUserMakeMoney(userId);
    	if(todayMakeMoney ==null)
    		return flag;
    	String todayYearRate =todayMakeMoney.getYearRate()==null?"0":Double.toString(todayMakeMoney.getYearRate());;
    	flag = NumberStringHelper.isGreater(yearRate, todayYearRate);
    	return flag;
    }
    
    public boolean compareLivingMoneyWithToday(String todayMoney,String userId) {
    	boolean flag = true;
    	FinanceUserMakeMoney todayMakeMoney = this.financeUserMakeMoneyService.getUserTodayFinanceUserMakeMoney(userId);
    	if(todayMakeMoney ==null)
    		return flag;
    	Double todayAmount =todayMakeMoney.getAmount()==null?0d:todayMakeMoney.getYearRate();;
    	flag = NumberStringHelper.isGreater(todayMoney,Double.toString(todayAmount));
    	return flag;
    }
    /**
     * 根据类型查询每个条件
     * @param type
     * @return
     */
    public LivingRate getLivingRateByType(LivingRateType type) {
    	LivingRate rate = this.livingRateDao.getRateByType(type.getType());
    	return rate ;
    }
    public LivingRate getgetLivingRateByType(String type){
    	LivingRate rate = this.livingRateDao.getRateByType(type);
    	return rate;
    } 
	public  String calLivingMoney(String yearRate,String commission) {
		String ratePercent =this.sysSettingService.getByKey(SysSettingType.COMMISSION_PERCENT.toString());
		ratePercent = NumberStringHelper.divString(ratePercent, "100", 2);
		yearRate = NumberStringHelper.divString(yearRate, "100", 2);
		String livingMoney = NumberStringHelper.mulString(commission, ratePercent);
		livingMoney = NumberStringHelper.mulString(livingMoney, yearRate);
		BigDecimal livingMoneyDecimal = new BigDecimal(livingMoney);
		BigDecimal days = new BigDecimal("365");
		livingMoney =livingMoneyDecimal.divide(days,6,BigDecimal.ROUND_HALF_UP).toString();
		//livingMoney = NumberStringHelper.divString(livingMoney,days,3);
		return NumberStringHelper.round(livingMoney,4);
	}
	/**
	 * 计算处消费类型外的其他所有类型最大百分比之和
	 * @return
	 */
	public Double getTotalMaxPercent(String id) {
		Double total = 0.0;
		// 除了消费类型之外的其他类型最大百分比数之和<=100
		LivingRateExample example = new LivingRateExample();
		Criteria criteria = example.createCriteria();
		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
		criteria.andTypeNotEqualTo(LivingRateType.Cousume.getType());
		if(StringHelper.isNotBlank(id)){
			criteria.andIdNotEqualTo(id);
		}
		List<LivingRate> list = this.livingRateDao.selectByExample(example);
		if (list.size() > 0) {
			for (LivingRate rate : list) {
				total = total + rate.getMaxPercent();
			}
		}
		return total;
	}
}